package com.ita.os.merchant.web.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileUploadBase;

import com.ita.os.merchant.po.Dish;
import com.ita.os.merchant.po.Merchant;
import com.ita.os.merchant.service.DishService;
import com.ita.os.merchant.service.MerchantService;
import com.ita.os.merchant.service.impl.DishServiceImpl;
import com.ita.os.merchant.service.impl.MerchantServiceImpl;
import com.ita.os.merchant.util.FileBean;
import com.ita.os.merchant.util.StringUtil;
import com.ita.os.merchant.util.UploadTool;

public class DishServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DishService dishService = new DishServiceImpl();
	private MerchantService merchantService = new MerchantServiceImpl();
	String savePath = "d:/upload";
	String tempPath = "d:/temp";
	String message = "";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String action=request.getParameter("action");
		if("preSave".equals(action)){
			dishPreSave(request,response);
		}else if("save".equals(action)){
			dishSave(request,response);
		}else if("backList".equals(action)){
			dishBackList(request,response);
		}else if("delete".equals(action)){
			dishDelete(request,response);
		}else if("update".equals(action)){
			dishUpdate(request,response);
		}
	}

	private void dishUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Merchant merchant = (Merchant)session.getAttribute("merchant");
		Merchant m = merchantService.findByName(merchant.getMname());
		if(m.getAudit().getStatus() == 0){
			request.setAttribute("message", "你还没有通过审核，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}else if(m.getAudit().getStatus() == 2){
			request.setAttribute("message", "你已经被拉黑，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}
		
		int mid = merchant.getMid();
		try {
			UploadTool uploadTool = new UploadTool();
			uploadTool.setRequest(request);
			uploadTool.setSavePath(savePath);
			uploadTool.setTempPath(tempPath);
			uploadTool.uploadFiles();

			FileBean fileBean = new FileBean();
			Map<String,String> fromDatas = uploadTool.getFormDatas();
			List<FileBean> fList = uploadTool.getFileBeanList();
			Dish dish = mapToDish(fromDatas);
			dish.setImg(fList.get(0).getFilePath());
			dish.setMid(mid);
			dishService.update(dish);
			message = "";
			System.out.println(dish);
		} catch (FileUploadBase.FileSizeLimitExceededException e) {
			e.printStackTrace();
			request.setAttribute("message", "单个文件超出最大值！！！");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		} catch (FileUploadBase.SizeLimitExceededException e) {
			e.printStackTrace();
			request.setAttribute("message", "上传文件的总的大小超出限制的最大值！！！");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		} catch (Exception e) {
			message = "文件上传失败！";
			e.printStackTrace();
		}
		 message = String.format(
	                "恭喜：%s,更新成功，将跳转到菜单列表！<meta http-equiv='refresh' content='2;url=%s'", 
	                merchant.getMname(),"dish?action=backList&mid=" + mid);
		request.setAttribute("message", message);
		request.getRequestDispatcher("/message.jsp").forward(request, response);
	}

	private void dishDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Merchant merchant = (Merchant)session.getAttribute("merchant");
		Merchant m = merchantService.findByName(merchant.getMname());
		if(m.getAudit().getStatus() == 0){
			request.setAttribute("message", "你还没有通过审核，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}else if(m.getAudit().getStatus() == 2){
			request.setAttribute("message", "你已经被拉黑，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}
		String did = request.getParameter("did");
		int count = dishService.delete(Integer.valueOf(did));
		int mid = merchant.getMid();
		request.getRequestDispatcher("dish?action=backList&mid=" + mid).forward(request, response);
	}

	private void dishBackList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Merchant merchant = (Merchant)session.getAttribute("merchant");
		Merchant m = merchantService.findByName(merchant.getMname());
		if(m.getAudit().getStatus() == 0){
			request.setAttribute("message", "你还没有通过审核，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}else if(m.getAudit().getStatus() == 2){
			request.setAttribute("message", "你已经被拉黑，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}
		List<Dish> dList = dishService.showAll(merchant.getMid());
		request.setAttribute("dList", dList);
		request.setAttribute("mainPage", "dishList.jsp");
		request.getRequestDispatcher("main.jsp").forward(request, response);
	}

	private void dishSave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Merchant merchant = (Merchant)session.getAttribute("merchant");
		Merchant m = merchantService.findByName(merchant.getMname());
		if(m.getAudit().getStatus() == 0){
			request.setAttribute("message", "你还没有通过审核，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}else if(m.getAudit().getStatus() == 2){
			request.setAttribute("message", "你已经被拉黑，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}
		int mid = merchant.getMid();
		try {
			UploadTool uploadTool = new UploadTool();
			uploadTool.setRequest(request);
			uploadTool.setSavePath(savePath);
			uploadTool.setTempPath(tempPath);
			uploadTool.uploadFiles();

			FileBean fileBean = new FileBean();
			Map<String,String> fromDatas = uploadTool.getFormDatas();
			List<FileBean> fList = uploadTool.getFileBeanList();
			Dish dish = mapToDish(fromDatas);
			dish.setImg(fList.get(0).getFilePath());
			dish.setMid(mid);
			dishService.insert(dish);
			
			message = "";
			System.out.println(dish);
		} catch (FileUploadBase.FileSizeLimitExceededException e) {
			e.printStackTrace();
			request.setAttribute("message", "单个文件超出最大值！！！");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		} catch (FileUploadBase.SizeLimitExceededException e) {
			e.printStackTrace();
			request.setAttribute("message", "上传文件的总的大小超出限制的最大值！！！");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		} catch (Exception e) {
			message = "文件上传失败！";
			e.printStackTrace();
		}
		 message = String.format(
	                "恭喜：%s,上传成功，将跳转到菜单列表！<meta http-equiv='refresh' content='2;url=%s'", 
	                merchant.getMname(),"dish?action=backList&mid=" + mid);
		request.setAttribute("message", message);
		request.getRequestDispatcher("/message.jsp").forward(request, response);
	}

	private void dishPreSave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Merchant merchant = (Merchant)session.getAttribute("merchant");
		Merchant m = merchantService.findByName(merchant.getMname());
		if(m.getAudit().getStatus() == 0){
			request.setAttribute("message", "你还没有通过审核，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}else if(m.getAudit().getStatus() == 2){
			request.setAttribute("message", "你已经被拉黑，不能编辑菜单！");
			request.setAttribute("mainPage", "default.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
			return;
		}
		String did = request.getParameter("did");
		if(StringUtil.isNotEmpty(did)){
			Dish dish = dishService.findById(Integer.valueOf(did));
			request.setAttribute("dish", dish);
			request.setAttribute("mainPage", "editDish.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
		}else{
			request.setAttribute("mainPage", "uploadDish.jsp");
			request.getRequestDispatcher("main.jsp").forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private Dish mapToDish(Map<String,String> map){
		Dish dish = new Dish();
		for(String key : map.keySet()){
			switch(key){
			case "did":
				dish.setDid(Integer.valueOf(map.get(key)));
				break;
			case "mid":
				dish.setMid(Integer.valueOf(map.get(key)));
				break;
			case "dname":
				dish.setDname(map.get(key));
				break;
			case "price":
				dish.setPrice(Integer.valueOf(map.get(key)));
				break;
			}
		}
		return dish;
	}

}
